<?php
namespace cms\modules\v1\models\shop;

use cms\modules\v1\models\Common;
use cms\modules\v1\models\supplier\Supplier;
use cms\modules\v1\models\user\User;
use common\models\Functions;
use common\models\Status;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\StringHelper;
use Yii;
/**
 * This is the model class for table "project_info".
 *
 * @property int $id
 * @property string $name
 */
class GoodsOrderDetail extends \common\models\shop\GoodsOrderDetail
{

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @param array $search
     * @return array
     */
    public function getListData($page = 1, $size = 20, $search = []) {
        try {

            //搜索条件
            $searchWhere  = $this->getSearch($search);//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'id DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);

            $data['data'] = $this->handelList($query);

            $data['summary'] = [
                ["key" => "id", "value" => '总计'],
                ["key" => "supplier", "value" => ''],
                ["key" => "goods", "value" => ''],
                ["key" => "goods_spec", "value" => ''],
                ["key" => "supplier_price", "value" => ''],
                ["key" => "nums", "value" => array_sum(array_column($data['data'],'nums'))],
                ["key" => "total_supplier_price", "value" =>array_sum(array_column($data['data'],'total_supplier_price'))],
                ["key" => "is_autogamy", "value" => ''],
                ["key" => "create_time", "value" => ''],
                ["key" => "do", "value" => ''],
            ];
            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 返回全部列表数据
     * @param array $search
     * @return array
     */
    public function getAllListData($search = []) {
        try {

            //搜索条件
            $searchWhere  = $this->getSearch($search);//自定义搜索条件
            //排序 order
            $orderSql = 'id DESC';
            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql);
            $return = $this->handelList($query);
            $return = $this->handelPrint($return);
            return Functions::formatRestAPI(0, '', $return);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @param $search
     * @return string
     */
    public function getSearch ($search = []) {
        $where = [];
        $where['is_arrive'] = Status::COMMON_RADIO_YES;
        $andWhere = [];
        $search = json_decode($search,true);
        if(!empty($search)){
            $status = isset($search['status']) ? $search['status'] : '';
            $orderNumber = isset($search['order_number']) ? $search['order_number'] : '';
            $goodsId = isset($search['goods_id']) ? $search['goods_id'] : '';
            $supplierId = isset($search['supplier_id']) ? $search['supplier_id'] : '';
            $isSelf = isset($search['is_self']) ? $search['is_self'] : '';
            $startTime = isset($search['start']) ? $search['start'] : '';
            $endTime = isset($search['end']) ? $search['end'] : '';

            if($status) {
                $where['status'] = $status;
            }


            if($isSelf) {
                $where['is_autogamy'] = $isSelf;
            }

            if($orderNumber) {
                $where['order_number'] = $orderNumber;
            }

            if($goodsId) {
                $where['goods_id'] = $goodsId;
            }

            if($supplierId) {
                $where['supplier_id'] = $supplierId;
            }

            if(!empty($startTime) && empty($endTime)) {
                $andWhere = ['>','create_time',$startTime];
            } elseif(empty($startTime) && !empty($endTime)) {
                $andWhere = ['<','create_time',$endTime];
            } elseif (!empty($startTime) && !empty($endTime)) {
                $dataStartAndEnd = Functions::getDay($startTime,$endTime);
                $andWhere = ['between','create_time',$dataStartAndEnd['start'], $dataStartAndEnd['end']];
            }
        }
        return [
            'where' => $where,
            'andWhere' => $andWhere
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelPrint($list = []) {
        $result = [];
        //先排序
        ArrayHelper::multisort($list,'goods_id');

        $list = ArrayHelper::index($list, null, 'supplier_id');
        //总数量
        $total = 0;
        //总自配
        $totalSelfMoney = 0;
        //总供应价
        $totalSupplier = 0;
        foreach ($list as $k => $v) {
            $goodsTmp = [];
            $supplierTotal = 0;
            foreach ($v as $kk => $vv) {
                $goodsTmp[] = [
                    'goods_image' => $vv['goods_image'],
                    'goods_name' => $vv['goods_name'],
                    'goods_spec' => $vv['goods_spec'],
                    'goods_id' => $vv['goods_id'],
                    'goods_price' => floatval($vv['goods_price']),
                    'supplier_price' => floatval($vv['supplier_price']),
                    'nums' => (int) $vv['nums'],
                    'total_supplier_price' => $vv['total_supplier_price'],
                    'is_autogamy' => $vv['is_autogamy'],
                    'autogamy_price' => floatval($vv['autogamy_price']),
                ];
                $total += (int) $vv['buy_num'];
                $supplierTotal += (int) $vv['buy_num'];
                if ($vv['is_autogamy'] == 1) {
                    $totalSelfMoney += $vv['autogamy_price'];
                }

                if ($vv['is_autogamy'] == 2) {
                    $totalSupplier += $vv['buy_num'] * $vv['supplier_price'];
                }
            }

        }

        $result['total'] = [
            'total_num' => $total,
            'total_self_money' => $totalSelfMoney,
            'total_supplier' => $totalSupplier,
            'date' => date('Y-m-d'),
        ];
        return $result;
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with([
            'goods',
            'goodsDetail',
            'supplier'
        ])->asArray()->all();
        foreach ($list as $k => $v) {
            $goodsInfo = ArrayHelper::getValue($v,'goods',[]);
            $goodsDetailInfo = ArrayHelper::getValue($v,'goodsDetail',[]);
            $supplierInfo = ArrayHelper::getValue($v,'supplier',[]);

            $list[$k]['supplier'] = $supplierInfo ? $supplierInfo['link_user'] : '';
            $list[$k]['supplier_id'] = $supplierInfo ? $supplierInfo['id'] : '';
            $list[$k]['goods_image'] = $goodsInfo ? $this->getImages($goodsInfo['main_image']) : '';
            $list[$k]['goods_name'] = $goodsInfo ? $goodsInfo['name'] : '';
            $list[$k]['goods_spec'] = $goodsDetailInfo ? $goodsDetailInfo['goods_spec'] : '';
            $list[$k]['goods_id'] = $v['goods_id'];
            $list[$k]['goods_price'] = floatval($v['goods_price']);
            $list[$k]['supplier_price'] = floatval($v['supplier_price']);
            $list[$k]['nums'] = (int) $v['buy_num'];
            $list[$k]['total_supplier_price'] = $v['buy_num'] * $v['supplier_price'];
            $list[$k]['is_autogamy'] = $v['is_autogamy'] == Status::COMMON_RADIO_YES;

        }
        return $list;
    }

    /**
     * 编辑订单信息
     * @return array
     */
    public function selfDelivery() {
        try {
            $post = Yii::$app->request->post();

            $id = (int) $post['id'];
            $money = $post['money'];
            if (!$money) {
                throw new Exception('自配价格不能为空');
            }

            $info = static::getOneInfoById($id);
            if ($info['is_autogamy'] !== Status::COMMON_RADIO_YES) {
                $res = static::updateData([
                    'is_autogamy' => Status::COMMON_RADIO_YES,
                    'autogamy_price' => $money,
                ], ['id' => $id]);
                if ($res === false) {
                    throw new Exception('系统错误');
                }
            }

            return Functions::formatRestAPI(0, '自配成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 订单详细信息
     * @param string $id
     * @return array
     */
    public function getFullInfo($id = '') {
        try {
            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $where['id'] = $id;
            $query = new \common\models\order\UserGoodsOrderDetail();
            $orderInfo = $query::getObjectOneByWhere($where)->with([
                'goods','goodsDetail'])->asArray()->one();
            if (empty($orderInfo)) {
                throw new Exception('未找到订单信息');
            }

            $goodsInfo = ArrayHelper::getValue($orderInfo,'goods',[]);
            $goodsDetailInfo = ArrayHelper::getValue($orderInfo,'goodsDetail',[]);

            $tmp = [
                'id' => $orderInfo['id'],
                'order_number' => $orderInfo['order_number'],
                'name' => $orderInfo['goods_name'],
                'is_print' => $orderInfo['is_print'],
                'is_arrive' => $orderInfo['is_arrive'],
                'image' => $goodsInfo && $goodsInfo['main_image'] ? $this->imageHost.$goodsInfo['main_image'] : '',
                'nums' => (int) $orderInfo['buy_num'],
                'price' => floatval($orderInfo['goods_price']),
                'supplier_price' => floatval($orderInfo['supplier_price']),
                'spec' => $goodsDetailInfo['goods_spec'],
            ];
            $data['orderInfo'] = $tmp;
            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
